// 购物车切片：管理购物车全局状态，并持久化到 localStorage
// 某些打包环境未导出 PayloadAction，这里不用它，直接用 any 代替以避免构建错误
import { createSlice, createSelector } from '@reduxjs/toolkit'

// 购物车条目类型定义
export interface CartItem {
  // 商品 SPU 或唯一 id
  shopSpuId: string
  // SKU 或规格 id（可选）
  skuId?: string
  // 展示字段：标题、图片、价格
  title: string
  image?: string
  price: number
  // 购买数量
  quantity: number
  // 额外标签（如 OTC）
  tag?: string
  // 已选规格文本（可选）
  selectedSpecsText?: string
  // 是否选中（用于结算）
  selected?: boolean
}

// 读取本地持久化
const loadFromStorage = (): CartItem[] => {
  try {
    const raw = localStorage.getItem('cart_items')
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

// 写入本地持久化
const saveToStorage = (items: CartItem[]) => {
  try {
    localStorage.setItem('cart_items', JSON.stringify(items))
  } catch {}
}

// Slice 状态
interface CartState { items: CartItem[] }

const initialState: CartState = {
  items: loadFromStorage(),
}

const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    // 加入购物车：同款同规格则合并数量
    addToCart: (state, action: any) => {
      const incoming = action.payload
      const exists = state.items.find(
        it => it.shopSpuId === incoming.shopSpuId && it.skuId === incoming.skuId
      )
      if (exists) {
        exists.quantity += incoming.quantity
      } else {
        // 新商品默认选中
        state.items.push({ ...incoming, selected: true })
      }
      saveToStorage(state.items)
    },
    // 更新数量
    updateQty: (state, action: any) => {
      const { shopSpuId, skuId, quantity } = action.payload
      const target = state.items.find(it => it.shopSpuId === shopSpuId && it.skuId === skuId)
      if (target) {
        target.quantity = Math.max(1, quantity)
        saveToStorage(state.items)
      }
    },
    // 移除
    removeFromCart: (state, action: any) => {
      const { shopSpuId, skuId } = action.payload
      state.items = state.items.filter(it => !(it.shopSpuId === shopSpuId && it.skuId === skuId))
      saveToStorage(state.items)
    },
    // 清空
    clearCart: (state) => {
      state.items = []
      saveToStorage(state.items)
    },
    // 切换单个商品选中状态
    toggleItemSelection: (state, action: any) => {
      const { shopSpuId, skuId } = action.payload
      const target = state.items.find(it => it.shopSpuId === shopSpuId && it.skuId === skuId)
      if (target) {
        target.selected = !target.selected
        saveToStorage(state.items)
      }
    },
    // 全选/取消全选
    toggleAllSelection: (state) => {
      const allSelected = state.items.every(item => item.selected)
      state.items.forEach(item => {
        item.selected = !allSelected
      })
      saveToStorage(state.items)
    }
  }
})

export const { addToCart, updateQty, removeFromCart, clearCart, toggleItemSelection, toggleAllSelection } = cartSlice.actions
export default cartSlice.reducer

// 选择器：获取购物车条目与数量、总价
export const selectCartItems = (state: any) => state.cart.items as CartItem[]
export const selectCartCount = (state: any) => (state.cart.items as CartItem[]).reduce((s, it) => s + it.quantity, 0)
export const selectCartTotal = (state: any) => (state.cart.items as CartItem[]).reduce((s, it) => s + it.quantity * it.price, 0)

// 使用 createSelector 优化选择器，避免不必要的重新渲染
export const selectSelectedItems = createSelector(
  [selectCartItems],
  (items) => items.filter(item => item.selected)
)

export const selectSelectedCount = createSelector(
  [selectSelectedItems],
  (selectedItems) => selectedItems.reduce((s, it) => s + it.quantity, 0)
)

export const selectSelectedTotal = createSelector(
  [selectSelectedItems],
  (selectedItems) => selectedItems.reduce((s, it) => s + it.quantity * it.price, 0)
)

// 是否全选状态
export const selectIsAllSelected = createSelector(
  [selectCartItems],
  (items) => items.length > 0 && items.every(item => item.selected)
)


